package com.wsdk.util;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.wsdk.Wsdk;
import com.wsdk.service.BluetoothLeService;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙工具类
 * 检测连接蓝牙的信息
 * @author fionera
 */
public class BlueToothScanUtil {
    private Context context;
    private static BluetoothAdapter bluetoothAdapter;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private boolean isScanning;
    private String macAddress;

    private Handler handler = new Handler(Looper.getMainLooper());

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device != null) {
                LogUtil.d("search bluetooth device:" + device.getAddress());
                addDeviceToList(device);
            }
        }
    };
    private Runnable dismissRunnable = new Runnable() {
        @Override
        public void run() {
            if (isScanning) {
                stopSearch(true);
                isScanning = false;
            }
        }
    };

    public BlueToothScanUtil(Context context) {
        this.context = context;
        BluetoothManager manager = (BluetoothManager) Wsdk.getInstance().getSystemService(
                Context.BLUETOOTH_SERVICE);
        if (manager != null) {
            bluetoothAdapter = manager.getAdapter();
        }
    }

    public void setMacAddress(String macAddress) {
        this.macAddress = macAddress;
    }

    public static boolean checkBTAvailable() {
        return Wsdk.getInstance().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE) && bluetoothAdapter != null;
    }

    public static boolean isBlueToothOpened() {
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

    private void addDeviceToList(BluetoothDevice device) {
        if (!devices.contains(device)) {
            if ("HMSoft".equals(device.getName())) {
                devices.add(device);
                checkDevicesList(devices);
            }
        }
    }

    private void checkDevicesList(final List<BluetoothDevice> devices) {
        if (devices.size() > 0) {
            BluetoothDevice connectedDevice = devices.get(devices.size() - 1);
            if (TextUtils.equals(connectedDevice.getAddress(), macAddress)) {
                if (isScanning) {
                    stopSearch(false);
                    isScanning = false;
                }
                connectDevice(connectedDevice);
                handler.removeCallbacks(dismissRunnable);
            }
        }
    }

    private void connectDevice(BluetoothDevice connectedDevice) {
        if (BluetoothLeService.isConnecting) {
            return;
        }
        Intent intent = new Intent(Wsdk.getInstance(), BluetoothLeService.class);
        intent.putExtra("DEVICE_ADDRESS", connectedDevice.getAddress());
        context.startService(intent);
    }

    public void startSearchBlueDevice() {
        LogUtil.d("search bluetooth device start:" + macAddress);
        if(bluetoothAdapter == null || isScanning){
            return;
        }
        isScanning = true;
        devices.clear();
        bluetoothAdapter.startLeScan(leScanCallback);
        handler.postDelayed(dismissRunnable, 8000);
    }

    public void stopSearch(boolean timeout) {
        LogUtil.d("search bluetooth device end:" + macAddress);
        if(bluetoothAdapter == null || !isScanning){
            return;
        }
        bluetoothAdapter.stopLeScan(leScanCallback);
        isScanning = false;
        if (stopSearchListener != null) {
            stopSearchListener.onStopped(timeout);
        }
        /*
          make sure remove runnable
         */
        handler.removeCallbacksAndMessages(null);
    }

    private StopSearchListener stopSearchListener;

    public void setStopSearchListener(StopSearchListener stopSearchListener) {
        this.stopSearchListener = stopSearchListener;
    }

    public interface StopSearchListener{
        /**
         * @param timeout 超时
         */
        void onStopped(boolean timeout);
    }
}
